package com.xinghai.web.controller.dingtalk;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.web.controller.dingtalk.dto.DingCallbackCrypto;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * 钉钉OA
 * 
 * @author xinghai
 */
@RestController
@RequestMapping("/api/dingtalk")
public class DingdingOaController extends BaseController
{


    @PostMapping("/getNotifity")
    public Map<String, String> list(@RequestParam(value = "msg_signature", required = false) String msg_signature,
                                    @RequestParam(value = "timestamp", required = false) String timeStamp,
                                    @RequestParam(value = "nonce", required = false) String nonce,
                                    @RequestBody(required = false) JSONObject json)
    {
        System.out.println(json);

        try {
            // 1. 从http请求中获取加解密参数

            // 2. 使用加解密类型
            // 2、调用订阅事件接口订阅的事件为企业级事件推送，此时OWNER_KEY为：开发者后台应用的Client ID（原企业内部应用 appKey )
            DingCallbackCrypto callbackCrypto = new DingCallbackCrypto("8OlGvpvvjRoUMGcMqGqUngHDTPhkm2XDMkpCSAnQm93PoUS9xdVUEU7U",
                    "lFS86mKocueXzNM9QtpHqUntM1TaTmbhjA67MG1YRwC",
                    "dingkabnb6nulsczm0oz");
            String encryptMsg = json.getString("encrypt");
            String decryptMsg = callbackCrypto.getDecryptMsg(msg_signature, timeStamp, nonce, encryptMsg);

            // 3. 反序列化回调事件json数据
            JSONObject eventJson = JSON.parseObject(decryptMsg);
            String eventType = eventJson.getString("EventType");

            // 4. 根据EventType分类处理
            if ("check_url".equals(eventType)) {
                // 测试回调url的正确性
//                bizLogger.info("测试回调url的正确性");
            } else if ("user_add_org".equals(eventType)) {
                // 处理通讯录用户增加事件
//                bizLogger.info("发生了：" + eventType + "事件");
            } else {
                // 添加其他已注册的
//                bizLogger.info("发生了：" + eventType + "事件");
            }

            // 5. 返回success的加密数据
            Map<String, String> successMap = callbackCrypto.getEncryptedMap("success");
            return successMap;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
